package com.trainfinder.requestor;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.Iterator;
import java.util.Map;

import com.trainfinder.proxy.Service;

public class LocalServiceImpl implements Service {

	private OutputStream outputSteam;

	private InputStream inputStream;

	public LocalServiceImpl(String resourceName, Map tokens,
			OutputStream outputSteam) {

		this.outputSteam = outputSteam;

		inputStream = totenReplaceStream(tokens, LocalServiceImpl.class
				.getResourceAsStream(resourceName));

	}

	public InputStream getInputStream() {
		if (inputStream == null) {
			return null;
		} else {
			InputStream result = new BufferedInputStream(inputStream);
			inputStream = null;
			return result;
		}
	}

	public OutputStream getOutputStream() {
		return outputSteam;
	}

	private InputStream totenReplaceStream(Map tokens, InputStream inputStream) {
		byte[] bytes = new byte[9024];
		StringBuffer buffer = new StringBuffer();
		try {
			while (true) {
				int count = inputStream.read(bytes, 0, bytes.length);

				if (count == -1) {
					break;
				} else {
					buffer.append(new String(bytes).substring(0, count));
				}

			}
		} catch (SocketException e) {
			// e.printStackTrace();

		} catch (IOException e) {
			// e.printStackTrace();

		}

		String result = buffer.toString();
		for (Iterator iter = tokens.entrySet().iterator(); iter.hasNext();) {
			Map.Entry entry = (Map.Entry) iter.next();

			result = result.replaceAll(entry.getKey().toString(), entry
					.getValue().toString());
		}

		return new ByteArrayInputStream(result.getBytes());

	}

	protected void finalize() throws Throwable {
		try {
			inputStream.close(); // close open files
		} finally {
			super.finalize();
		}
	}

	public void close() {
		try {
			if (inputStream != null) {
				inputStream.close();
			}
		} catch (IOException e) {
			//
		}
		try {
			if (outputSteam != null) {
				outputSteam.close();
			}
		} catch (IOException e) {
			//
		}

	}
}
